/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, {Component} from 'react';
import {
    Button,
    Dimensions,
    ListView,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    TextInput,
    View,
    Alert,
    FlatList,
    TouchableHighlight, StatusBar, Image, TouchableOpacity
} from 'react-native';
import Swiper from "react-native-swiper";


const instructions = Platform.select({
    ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
    android:
    'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});
const ds = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 != r2
})
const screenWidth = Dimensions.get("window").width;
//指示器的大小
const circleSize = 8;
const circleMargin = 5;
export default class Home extends Component<Props> {
    // noinspection JSAnnotator
    constructor(props) {
        super(props)
        this.state = {
            currentPage: 0,
            searchText: '',
            dataSource: ds.cloneWithRows([
                {
                    image: require('./image/product-image-01.jpg'),
                    title: '商品1',
                    subTitle: '描述1'
                },
                {
                    image: require('./image/product-image-02.jpg'),
                    title: '商品2',
                    subTitle: '描述2'
                },
                {
                    image: require('./image/product-image-03.jpg'),
                    title: '商品3',
                    subTitle: '描述3'
                },
                {
                    image: require('./image/product-image-01.jpg'),
                    title: '商品4',
                    subTitle: '描述4'
                },
                {
                    image: require('./image/product-image-02.jpg'),
                    title: '商品5',
                    subTitle: '描述5'
                },
                {
                    image: require('./image/product-image-03.jpg'),
                    title: '商品6',
                    subTitle: '描述6'
                },
                {
                    image: require('./image/product-image-01.jpg'),
                    title: '商品7',
                    subTitle: '描述7'
                },
                {
                    image: require('./image/product-image-02.jpg'),
                    title: '商品8',
                    subTitle: '描述8'
                },
                {
                    image: require('./image/product-image-03.jpg'),
                    title: '商品9',
                    subTitle: '描述9'
                },
                {
                    image: require('./image/product-image-01.jpg'),
                    title: '商品10',
                    subTitle: '描述10'
                }
            ]),
            flatData: [
                {
                    key: 0,
                    image: require('./image/product-image-01.jpg'),
                    title: '商品1',
                    subTitle: '描述1'
                },
                {
                    key: 1,
                    image: require('./image/product-image-02.jpg'),
                    title: '商品2',
                    subTitle: '描述2'
                },
                {
                    key: 2,
                    image: require('./image/product-image-03.jpg'),
                    title: '商品3',
                    subTitle: '描述3'
                },
                {
                    key: 3,
                    image: require('./image/product-image-01.jpg'),
                    title: '商品4',
                    subTitle: '描述4'
                },
                {
                    key: 4,
                    image: require('./image/product-image-02.jpg'),
                    title: '商品5',
                    subTitle: '描述5'
                },
                {
                    key: 5,
                    image: require('./image/product-image-03.jpg'),
                    title: '商品6',
                    subTitle: '描述6'
                },
                {
                    key: 6,
                    image: require('./image/product-image-01.jpg'),
                    title: '商品7',
                    subTitle: '描述7'
                },
                {
                    key: 7,
                    image: require('./image/product-image-02.jpg'),
                    title: '商品8',
                    subTitle: '描述8'
                },
                {
                    key: 8,
                    image: require('./image/product-image-03.jpg'),
                    title: '商品9',
                    subTitle: '描述9'
                },
                {
                    key: 9,
                    image: require('./image/product-image-01.jpg'),
                    title: '商品10',
                    subTitle: '描述10'
                }
            ],
            advertisements: [
                {
                    // title: '广告1',
                    // backgroundColor: 'gray'
                    url: 'https://upload.jianshu.io/admin_banners/web_images/4583/40bca38a47b32bdc04a1997a6ac9e76951217c18.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/1250/h/540'
                },
                {
                    // title: '广告二',
                    // backgroundColor: 'orange'
                    url: 'https://upload.jianshu.io/admin_banners/web_images/4586/2eff4db8c6dac6253049da311e4f65359e075775.jpeg?imageMogr2/auto-orient/strip|imageView2/1/w/1250/h/540'
                },
                {
                    // title: '广告三',
                    // backgroundColor: 'yellow'
                    url: 'https://upload.jianshu.io/admin_banners/web_images/4581/b346d0388557ad1a1b514d185340ac6886192dc9.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/1250/h/540'
                },
            ],
            productImages: [
                {image: require('./image/product-image-01.jpg')},
                {image: require('./image/product-image-02.jpg')},
                {image: require('./image/product-image-03.jpg')},
            ]
        };
        this._renderRow = this._renderRow.bind(this);
        this._rendItem = this._rendItem.bind(this);
    }

    static defaultProps = {
        duration: 1000,
    }

    componentDidMount() {
        // this._startTimer()
        console.log("组件加载完成")
    }

    componentWillUnmount() {
        clearInterval(this.interval)
    }

    _startTimer() {
        this.interval = setInterval(() => {
            let nextPage = this.state.currentPage + 1
            if (nextPage >= 3) {
                nextPage = 0;
            }
            this.setState({currentPage: nextPage})
            const offsetX = nextPage * Dimensions.get('window').width;
            this.refs.scroll.scrollResponderScrollTo({x: offsetX, y: 0, animated: true})
        }, 4000)
    }

    _renderRow = (rowData, sectionId, rowId) => {
        return (
            <TouchableHighlight onPress={() =>
                Alert.alert('你单击了商品列表')}>
                <View style={styles.row}>
                    <Image source={rowData.image} style={styles.productImage}></Image>
                    <View style={styles.productText}>
                        <Text style={styles.productTitle}>{rowData.title}</Text>
                        <Text style={styles.productSubTitle}>{rowData.subTitle}</Text>
                    </View>

                </View>
            </TouchableHighlight>
        );
    }

    _rendItem = (item) => {
        return (
            <TouchableOpacity onPress={() =>
                this.props.navigation.navigate('goodsDetail',{
                    content:'你有点坏哦',callback:(backData)=>{Alert.alert(backData)}
                })}>
                <View style={styles.row}>
                    <Image source={item.item.image} style={styles.productImage}></Image>
                    <View style={styles.productText}>
                        <Text style={styles.productTitle}>{item.item.title}</Text>
                        <Text style={styles.productSubTitle}>{item.item.subTitle}</Text>
                    </View>

                </View>
            </TouchableOpacity>
        );
    }

    _renderSeperator(sectionId, rowId, adjustRowHightlighted) {
        return (
            <View key={'${}'}></View>
        )
    }

    /**开始拖拽 */
    _onScrollBeginDrag() {
        console.log("开始拖拽");
        //两种清除方式 都是可以的没有区别
        // this.timer && clearInterval(this.timer);
        this.timer && clearTimeout(this.timer);
    }

    /**停止拖拽 */
    _onScrollEndDrag() {
        console.log("停止拖拽");
        //this.timer && this._startTimer();
    }


    render() {
        const advertisementCount = this.state.advertisements.length;
        //计算指示器的宽度
        const indicatorWidth = circleSize * advertisementCount + circleMargin * advertisementCount * 2;
        //计算指示器最左边的坐标位置
        const left = (screenWidth - indicatorWidth) / 2
        return (
            <View style={styles.container}>
                {/*状态栏*/}
                <StatusBar backgroundColor='white' barStyle={'dark-content'}/>
                {/*搜索框*/}
                <View style={styles.searchbar}>
                    <TextInput style={styles.input} placeholder='搜索商品'
                               onChangeText={(text) => {
                                   this.setState({searchText: text});
                                   console.log('输入的内容是: ' + this.state.searchText)
                               }}/>
                    <Button style={styles.button} title='搜索'
                            onPress={() => Alert.alert('搜索内容' + this.state.searchText, null, null)}
                    />
                </View>
                {/*轮播广告*/}
                <View style={styles.advertisement}>
                    {/*轮播广告--rn自己写的*/}
                    {/*<ScrollView ref='scroll'*/}
                    {/*horizontal={true}*/}
                    {/*showsHorizontalScrollIndicator={false}*/}
                    {/*pagingEnabled={true}*/}
                    {/*// 滑动完一贞*/}
                    {/*onMomentumScrollEnd={(scroll) => {*/}

                    {/*//求出偏移量*/}
                    {/*let offsetX = scroll.nativeEvent.contentOffset.x;*/}
                    {/*//求出当前页数*/}
                    {/*let pageIndex = Math.floor(offsetX / screenWidth);*/}
                    {/*this.setState({currentPage: pageIndex})*/}
                    {/*}}*/}
                    {/*// //开始拖拽*/}
                    {/*//         onScrollBeginDrag={() => {*/}
                    {/*//             this._onScrollBeginDrag().bind(this)*/}
                    {/*//         }}*/}
                    {/*// //结束拖拽*/}
                    {/*//         onScrollEndDrag={() => {*/}
                    {/*//             this._onScrollEndDrag().bind(this)*/}
                    {/*//         }}*/}

                    {/*>*/}
                    {/*{*/}
                    {/*this.state.advertisements.map((advertisement, index) => {*/}
                    {/*return (*/}
                    {/*<TouchableOpacity key={index} onPress={() =>{*/}
                    {/*this.props.navigation.navigate('goodsDetail',{*/}
                    {/*content:'你真帅'*/}
                    {/*})*/}
                    {/*}}>*/}
                    {/*<Text style={[*/}
                    {/*styles.advertisementContent, {backgroundColor: advertisement.backgroundColor}*/}
                    {/*]}>{advertisement.title}*/}
                    {/*</Text>*/}
                    {/*{console.log(advertisement.url)}*/}
                    {/*<Image*/}
                    {/*style={styles.advertisementContent}*/}
                    {/*/*source={require('./image/reba.jpg')}*/}
                    {/*source={{uri: advertisement.url}}*/}
                    {/*>*/}
                    {/*</Image>*/}

                    {/*</TouchableOpacity>);*/}
                    {/*})*/}
                    {/*}*/}
                    {/*</ScrollView>*/}
                    {/*指示器*/}
                    {/*<View style={[styles.indictor, {left: left}]}>*/}
                    {/*{*/}
                    {/*this.state.advertisements.map((advertisement, index) => {*/}
                    {/*return (*/}
                    {/*<View key={index}*/}
                    {/*style={(index === this.state.currentPage) ? styles.circleSelected : styles.circle}>*/}
                    {/*</View>);*/}
                    {/*})*/}
                    {/*}*/}
                    {/*</View>*/}
                    {/*用三方组件 swiper 实现图片轮播*/}
                    <Swiper loop={true} height={190} autoplay={true} showsPagination={false}>
                        {
                            this.state.advertisements.map((advertisement, index) => {
                                return (
                                    <TouchableOpacity key={index} onPress={() => {
                                        this.props.navigation.navigate('home2', {
                                            content: '你真帅'
                                        })
                                    }}>
                                        <Image
                                            style={styles.advertisementContent}
                                            // source={require('./image/reba.jpg')}
                                            source={{uri: advertisement.url}}
                                        />
                                    </TouchableOpacity>
                                );
                            })
                        }
                    </Swiper>
                </View>
                {/*商品列表*/}
                <View style={styles.goodsList}>
                    {/*<ListView dataSource={this.state.dataSource} showsVerticalScrollIndicator={false}*/}
                    {/*renderRow={this._renderRow}/>*/}
                    <FlatList data={this.state.flatData}
                        // ListHeaderComponent={this._header}
                        // ListFooterComponent={this._footer}
                              ItemSeparatorComponent={this._separator}
                              renderItem={this._rendItem.bind(this)}
                              onRefresh={this.refreshing}
                              refreshing={false}
                              onEndReachedThreshold={0}
                              onEndReached={
                                  this._onload
                              }
                        //默认情况下每行都需要提供一个不重复的key属性
                              keyExtractor={(item, index) => (index.toString())}/>
                </View>
            </View>
        );
    }

    refreshing() {
        let timer = setTimeout(() => {
            clearTimeout(timer)
            alert('刷新成功')
        }, 1500)
    }

    _onload() {
        let timer = setTimeout(() => {
            clearTimeout(timer)
            alert('加载成功')
        }, 1500)
    }

    _header = () => {
        return <Text style={[styles.txt, {backgroundColor: 'white'}]}>这是头部</Text>;
    }

    _footer = () => {
        return <Text style={[styles.txt, {backgroundColor: 'white'}]}>这是尾部</Text>;
    }

    _separator = () => {
        return <View style={{height: 2, backgroundColor: 'gray'}}/>;
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    //搜索栏的样式
    searchbar: {
        marginTop: Platform.OS === 'ios' ? 20 : 0,
        height: 60,
        justifyContent: 'center',
        alignItems: 'center',
        flexDirection: 'row',
        paddingLeft: 20,
        paddingRight: 20
    },
    //搜索商品的输入框的样式
    input: {
        flex: 1,
        borderColor: 'gray',
        height: 40,
        borderWidth: 2,
        borderRadius: 10,
        paddingLeft: 30,
        marginRight: 15,
    },
    //搜索商品按钮的样式
    button: {
        flex: 1,
    },
    //轮播广告的样式
    advertisement: {
        height: 180,
        // backgroundColor: 'green',
        // justifyContent: 'center',
        // alignItems: 'center'
    },
    //轮播广告content的样式
    advertisementContent: {
        width: Dimensions.get('window').width,
        height: 180,
    },
    //商品列表的样式
    goodsList: {
        flex: 1,
        backgroundColor: 'blue',
        justifyContent: 'center',
        alignItems: 'center'
    },
    //商品列表的item的样式
    row: {
        width: screenWidth,
        flexDirection: 'row',
    },
    productImage: {
        marginHorizontal: 10,
        width: 40,
        height: 40,
        alignSelf: 'center'
    },
    productText: {
        flex: 1,
        marginVertical: 5
    },
    productTitle: {
        flex: 3,
        fontSize: 16
    },
    productSubTitle: {
        flex: 2,
        fontSize: 14,
        color: 'gray'
    },
    //指示器的样式
    indictor: {
        position: 'absolute',
        top: 160,
        flexDirection: 'row'
    },
    //未选中指示器的样式
    circle: {
        width: circleSize,
        height: circleSize,
        borderRadius: circleSize / 2,
        backgroundColor: 'gray',
        marginHorizontal: circleMargin
    },
    //选中指示器的样式
    circleSelected: {
        width: circleSize,
        height: circleSize,
        borderRadius: circleSize / 2,
        backgroundColor: 'white',
        marginHorizontal: circleMargin
    }
});
